<template>
  <el-dialog :title="titleRegion" append-to-body :close-on-click-modal="false" @close="closeDialog()" v-model="visible">
    <el-form :model="dataForm" :rules="dataRule" ref="dataForm" @keyup.enter.native="dataFormSubmit()"
      label-width="110px">
      <el-row>
        <el-col :span="12">
          <el-form-item label="停车场" prop="parkId">
            <el-select v-model="dataForm.parkId" class="m-2" placeholder="所在停车场">
              <el-option v-for="item in parkNames" :key="item.id" :label="item.parkName" :value="item.id" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="区域名称" prop="regionName">
            <el-input v-model="dataForm.regionName" placeholder="区域名称"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="区域级别" prop="level">
            <el-select v-model="dataForm.level" clearable class="m-2" placeholder="区域级别">
              <el-option v-for="item in dicts.region_level" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">

          <el-form-item label="车位数" prop="spaceNum">
            <el-input v-model="dataForm.spaceNum" placeholder="车位数"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="是否安装硬件" prop="isHardware">
            <el-radio-group v-model="dataForm.isHardware">
              <el-radio label="0" border>否</el-radio>
              <el-radio label="1" border>是</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="12"></el-col>
      </el-row>

      <el-row>
        <el-col :span="24">
          <el-form-item label="详细地址" prop="address">
            <el-autocomplete style="width:100%" v-model="dataForm.address" :trigger-on-focus="true"
              :fetch-suggestions="querySearchAsync" placeholder="详细地址" @select="handleSelect" clearable>
            </el-autocomplete>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="12">
          <el-form-item label="经度" prop="longitude">
            <el-input v-model="dataForm.longitude" placeholder="经度"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="纬度" prop="latitude">
            <el-input v-model="dataForm.latitude" placeholder="纬度"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <div style="width:100%;height:300px;border:1px solid">
        <el-bmap ref="map" :preserve-drawing-buffer="true" :heading="heading" :center="center" :zoom="zoom"
          @click="getInfo" />
      </div>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="close()">取消</el-button>
        <el-button type="primary" @click="dataFormSubmit()">确定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script>
import { getObj, addObj, putObj } from '@/api/roadStop/regionroad'

export default {
  props: ["parkName"],
  dicts: ["region_level"],
  data () {
    return {
      zoom: 16,
      center: [121.59996, 31.197646],
      //   tilt: 60,
      heading: 0,
      visible: false,

      dataForm: {
      },
      dataRule: {
        parkId: [
          { required: true, message: '停车场id不能为空', trigger: 'blur' }
        ],

        regionName: [
          { required: true, message: '区域名称不能为空', trigger: 'blur' }
        ],

        spaceNum: [
          { required: true, message: '车位数不能为空', trigger: 'blur' }
        ],

        level: [
          { required: true, message: '区域级别不能为空', trigger: 'blur' }
        ],

        isHardware: [
          { required: true, message: '是否安装硬件不能为空', trigger: 'blur' }
        ],

        address: [
          { required: true, message: '详细地址不能为空', trigger: 'blur' }
        ],

        longitude: [
          { required: true, message: '经度不能为空', trigger: 'blur' }
        ],

        latitude: [
          { required: true, message: '纬度不能为空', trigger: 'blur' }
        ],

      },
      parkNames: [],
      titleRegion: null
    }
  },
  methods: {
    initMap (point) {
      this.mk = new BMapGL.Marker(point, { enableDragging: true }) //创建一个图像标注实例，enableDragging：是否启用拖拽，默认为false
      this.$refs.map.$$getInstance().addOverlay(this.mk) //将覆盖物添加到地图中
      //   console.log(this.mk);
    },
    getInfo (e) {
      //   console.log(e);
      this.dataForm.latitude = parseFloat(e.latlng.lat).toFixed(6)
      this.dataForm.longitude = parseFloat(e.latlng.lng).toFixed(6)
      this.$refs.map.$$getInstance().clearOverlays() //清除地图上所有覆盖物
      this.mk = new BMapGL.Marker(e.latlng) //根据所选坐标重新创建Marker
      this.$refs.map.$$getInstance().addOverlay(this.mk) //将覆盖物重新添加到地图中
      this.getAddrByPoint(e.latlng)
      this.initMap(e.latlng)
    },
    getAddrByPoint (point) {
      var that = this;
      var geco = new BMapGL.Geocoder();
      geco.getLocation(point, function (res) {
        // console.log(res)  //内容见下图
        that.dataForm.address = res.address
        that.mk.setPosition(point) //重新设置标注的地理坐标
        that.$refs.map.$$getInstance().panTo(point)  //将地图的中心点更改为给定的点
        that.dataForm.address = res.address;  //记录该点的详细地址信息
        that.dataForm.addrPoint = point;  //记录当前坐标点
      })
    },
    querySearchAsync (str, callback) {
      var options = {
        onSearchComplete: function (res) { //检索完成后的回调函数
          //   console.log(res);
          var s = [];

          if (local.getStatus() == BMAP_STATUS_SUCCESS) {
            for (var i = 0; i < res.getCurrentNumPois(); i++) {
              // 数组中的每一项都是一个对象，对象中必须要有value属性，否则不能显示，有没有别的属性不影响。原因是因为源码中定义的就是value字段
              res.getPoi(i).value = res.getPoi(i).address + res.getPoi(i).title
              s.push(res.getPoi(i));
            }
            callback(s) //获取到数据时，通过回调函数cb返回到<el-autocomplete>组件中进行显示
            // console.log(s);
          } else {
            callback(s)
          }
        }
      }
      //   console.log(this.result);
      //   console.log(this.$refs.map.$$getInstance());
      var local = new BMapGL.LocalSearch(this.$refs.map.$$getInstance(), options) //创建LocalSearch构造函数
      local.search(str) //调用search方法，根据检索词str发起检索
      //   console.log(str);
      //   console.log(cb);
    },
    handleSelect (item) {
      // console.log(item.point);
      this.dataForm.address = item.address + item.title; //记录详细地址，含建筑物名
      this.dataForm.latitude = parseFloat(item.point.lat).toFixed(6)
      this.dataForm.longitude = parseFloat(item.point.lng).toFixed(6)
      //   this.form.addrPoint = item.point; //记录当前选中地址坐标
      this.$refs.map.$$getInstance().clearOverlays() //清除地图上所有覆盖物
      //   console.log(item.point);
      this.mk = new BMapGL.Marker(item.point) //根据所选坐标重新创建Marker
      this.$refs.map.$$getInstance().addOverlay(this.mk) //将覆盖物重新添加到地图中
      this.$refs.map.$$getInstance().panTo(item.point) //将地图的中心点更改为选定坐标点
    },
    init (id) {
      if (id == undefined) {
        this.titleRegion = '新增'
      } else {
        this.titleRegion = '修改'
        this.$nextTick(() => {
          this.$refs['dataForm'].resetFields()
          if (id) {
            getObj(id).then(response => {
              this.dataForm = response.data.data
            })
          }
        })
      }

      this.parkNames = this.parkName
      this.visible = true;

    },
    close () {
      this.visible = false;
      this.dataForm = {}
    },
    // 表单提交
    dataFormSubmit () {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          if (this.titleRegion == '修改') {
            putObj(this.dataForm).then(data => {
              this.$notify.success('修改成功')
              this.visible = false
              this.$emit('refreshDataList')
            })
          } else {
            addObj(this.dataForm).then(data => {
              this.$notify.success('添加成功')
              this.visible = false
              this.$emit('refreshDataList')
            })
          }
        }
      })
    },
    //重置表单
    closeDialog () {
      this.dataForm = {}
      this.$refs["dataForm"].resetFields()
    }
  }
}
</script>
